import {UserModel} from './user.model'
import { connection } from '../app/database/mysql'

interface GetUserOptions{
    password?:boolean;
}

export const getUser=(condition:string)=>{ // 条件 where 抽象 万金油查询方法
    return async(param:string|number,option:GetUserOptions={})=>{
        // getUserByName
        // getUserById
        // getUserByPasswordAndName
        const {password} = option;

        const statement =` 
            SELECT
                user.id,
                user.name,
                IF(
                    COUNT(avatar.id),1,NULL
                ) as avatar
                ${password ? ',password':''}
            FROM 
                user
            LEFT JOIN avatar
                ON avatar.userId = user.id
            WHERE
                ${condition} = ?
        `;
        const [data]=await connection.promise().query(statement,param)
        return data[0].id ? data[0]:null
    }
}

export const getUserByName=getUser('user.name')

export const createUser=async(user:UserModel)=>{
    // 准备查询
    try {
            
        const statement = `
            INSERT INTO user
            SET ?
        `
        const [data] = await connection.promise().query(statement,user)
        console.log(data)
    } catch (error) {
        
    }
    return {
        id:1
    }
}

export const getUserById=getUser('user.id')

export const updataUser = async (userId : number ,userData:UserModel)=>{
    const statement = `
        UPDATE user
        SET ?
        WHERE user.id = ?
    `
    const params = [userData,userId];
    const [data] = await connection.promise().query(statement,params)
    return data
}